package com.vim.common.utils;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

public class HttpClientUtils {

    /**
     * 发送请求
     * @param url    请求地址
     * @param method 请求类型 GET\POST
     * @param params 请求参数
     */
    public static String send(String url, RequestMethod method, List<NameValuePair> params){
        CloseableHttpClient client = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            //请求信息
            params = null == params ? new ArrayList<>() : params;
            URI uri = new URIBuilder(url).setParameters(params).build();
            HttpRequestBase request = null;
            if(method.equals(RequestMethod.GET)){
                request = new HttpGet(uri);
            }else{
                request = new HttpPost(uri);
            }

            //请求配置
            RequestConfig config = RequestConfig.custom()
                    .setConnectTimeout(10000)
                    .setConnectionRequestTimeout(10000)
                    .setSocketTimeout(10000)
                    .setRedirectsEnabled(true).build();
            request.setConfig(config);

            //发送请求
            response = client.execute(request);
            if(response.getStatusLine().getStatusCode() != 204){
                HttpEntity entity = response.getEntity();
                return EntityUtils.toString(entity);
            }else{
                return "";
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args) {
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("loginName", "admin"));
        params.add(new BasicNameValuePair("password", "123456"));
        String result = HttpClientUtils.send("http://localhost:8080/api/api/user/login", RequestMethod.POST, params);
        System.out.println(result);
    }
}